package com.stx.chat.service.impl;

import com.stx.chat.dao.UserDao;
import com.stx.chat.entity.User;
import com.stx.chat.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Override
    public boolean register(String username, String password) {


        /**
         * username去数据表中查询是否存在同名用户，存在的话返回false
         * 否则注册成功
         */
        User user = userDao.selectUserByUsername(username);

        //用户名重复
        if (user!=null){
            return false;

        }else {
            Date nowDate = new Date();
            String avatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgaitaobao4.alicdn.com%2Ftfscom%2Fi3%2F3163790567%2FTB1_MIahAomBKNjSZFqXXXtqVXa_%21%210-item_pic.jpg_300x300q90.jpg&refer=http%3A%2F%2Fgaitaobao4.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623316989&t=6cad35ce2b168aba8afe0cace2ef1596";
            String newPwd = DigestUtils.md5Hex(password);
            userDao.register(username,newPwd,nowDate,avatar);

            return true;

        }

    }

    @Override
    public User login(String username, String password) {

        //从数据库中获取user对象，password是MD5加密的密文
        User user = userDao.selectUserByUsername(username);
        if (user!=null){

            String pwd = DigestUtils.md5Hex(password);
            //账号密码校验通过，返回user
            if (pwd.equals(user.getPassword())){
                return user;
            }else {
                return null;
            }

        }else {
            return null;
        }

    }
}
